var defaultOptions = require('./config')

var http = require("http");
var fs = require("fs");
var path = require("path");
var querystring = require("querystring");
var exec = require('child_process').exec;
var log = logStartText = "The log is empty.";
var util = require('util');
var server = http.createServer();
var options = {}; // extend the options
if (fs.existsSync(path.join(__dirname, '../package.json'))) {
    packageInformation = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'));
}
exports.packageInformation = packageInformation;
exports.defaultOptions = defaultOptions;
exports.init = function(newOptions, callback) {

    // Handle arguments
    if (typeof newOptions == "function") {
        callback = newOptions;
        delete newOptions;
    }


    // Merge options
    for (var key in defaultOptions) {
        options[key] = defaultOptions[key];
    }

    for (var key in newOptions) {
        options[key] = newOptions[key];
    }


    // Lets create the server
    server = http.createServer(function(req, res) {
        // Handle requests
        var data = "";
        req.on("data", function(chunk) {
            data += chunk;
        });
        req.on("end", function() {
            req.params = {};
            if (req.method == "POST") {
                req.body = querystring.parse(data);
            } else {
                req.body = {};
            }

            if (res.finished) {
                return;
            }

            if (req.url != '/webhook') {
                res.statusCode = 404;
                res.write("404 Not Found");
                res.end();
            } else {
                var hook = JSON.parse(req.body.hook);
                //验证密码
                if (hook.password != options.password) {
                    exports.log('password is error!');
                    res.write("500 password error");
                    res.end();
                } else {
                    exports.log('password is verified!');
                }
                //验证分支
                if (hook.push_data.ref != options.branch) {
                    exports.log('branch is error!');
                    res.write("500 branch error");
                    res.end();
                } else {
                    exports.log('branch is verified!');
                }
                runDeploy(options.deploy);
                res.write('{"status":"ok"}');
                res.end();
            }

        });

    });


    server.on('error', function(err) {
        console.log("error", err);
    });

    // Start server
    server.listen(options.port);
    console.log('Started');
    return server;
}
exports.stop = function(callback) {
    server.close();
    setTimeout(callback, 300);
};
exports.clearLog = function() {
    log = "";
};
exports.log = function(message) {
    fs.appendFile(options.log, message, 'utf8', function(err) {
        if (err) {
            console.log(err);
        }
    });
    console.log(message);
    return exports;
};
exports.server = server;

function runDeploy(deploy) {
    var localPath = path.resolve(deploy.basepath);
    exec(deploy.command, {
        cwd: localPath,
        encoding: "buffer"
    }, function(error, stdout, stderr) {
        if (error) {
            // if (process.platform.indexOf('win') >= 0) {
            //     var iconv = require('iconv-lite');
            //     error.message = iconv.decode(stderr, 'gbk');
            // }
            exports.log(">  ERROR: " + error.message);
        }
        exports.log("> DONE!");
    });
}